package io.yuncheng.common.utils;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import io.yuncheng.modules.sys.entity.SubAppAssessmentSplitEntity;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.*;

/**
 * 文件工具类
 */
public class FileUtil {

    public static final String FILEPATH = "./file";

    public  void  downloadByData(HttpServletResponse response, List<SubAppAssessmentSplitEntity> list, String fileName) throws Exception{
        TemplateExportParams params = new TemplateExportParams(
                "./template/assessment_template.xls");
        Map<String, Object> map = new HashMap<String, Object>(4);
        map.put("maplist", list);
        Workbook workbook = ExcelExportUtil.exportExcel(params, map);
        exportExcelByDownload(workbook,response,fileName);
    }

     public static void exportExcelByDownload(Workbook wb,HttpServletResponse response,String fileName) throws UnsupportedEncodingException {
         response.reset(); // 清除buffer缓存
         // 指定下载的文件名
         response.setHeader("Content-Disposition", "attachment;filename=" +  URLEncoder.encode(fileName, "UTF-8") );
         response.setContentType("application/vnd.ms-excel;charset=UTF-8");
         response.setHeader("Pragma", "no-cache");
         response.setHeader("Cache-Control", "no-cache");
         response.setDateHeader("Expires", 0);
         response.setHeader("fileName",fileName);
         response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");

         try {
             OutputStream output;
             try {
                 output = response.getOutputStream();
                 BufferedOutputStream bufferedOutPut = new BufferedOutputStream(output);
                 bufferedOutPut.flush();
                 wb.write(bufferedOutPut);
                 bufferedOutPut.close();
             } catch (Exception e) {
                 e.printStackTrace();
             }
         } catch (Exception e1) {
             e1.printStackTrace();
         }
      }
    public static  void downLoadFile(HttpServletResponse response,String filepath ) throws Exception{
        // 如果文件名不为空，则进行下载
        if (filepath != null) {
            File file = new File(filepath);
            // 如果文件存在，则进行下载
            if (file.exists()) {
                // 配置文件下载
                response.setHeader("content-type", "application/octet-stream");
                response.setContentType("application/octet-stream");
                // 下载文件能正常显示中文
                response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(file.getName(), "UTF-8"));
                // 实现文件下载
                byte[] buffer = new byte[1024];
                FileInputStream fis = null;
                BufferedInputStream bis = null;
                try {
                    fis = new FileInputStream(file);
                    bis = new BufferedInputStream(fis);
                    OutputStream os = response.getOutputStream();
                    int i = bis.read(buffer);
                    while (i != -1) {
                        os.write(buffer, 0, i);
                        i = bis.read(buffer);
                    }
                    System.out.println("Download  successfully!");

                } catch (Exception e) {
                    System.out.println("Download  failed!");
                } finally {
                    if (bis != null) {
                        try {
                            bis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (fis != null) {
                        try {
                            fis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
    }
    /**
     * 保存文件到
     * @param file
     * @param uuid
     * @return
     */
    public static String  saveFile(MultipartFile file,String uuid){
        try {
            /**
             *  这里的路径(可以自定义)
             */
            String filePath = FILEPATH;
            /**
             * 获取图片上传的文件路径
             */
            File picFile = new File(filePath);
            /**
             *  判断文件夹是否存在,如果不存在就创建
             */
            if (!picFile.isDirectory()) {
                picFile.mkdirs();//mkdir创建单层文件夹；mkdirs创建多层文件夹
            }
            /**
             *  文件后缀
             */
            String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
            /**
             *  生成新的文件名（UUID加入+_+文件id）避免冲突
             */
            String originalFilename = picFile + "/" + uuid + suffix;
            if (!org.springframework.util.StringUtils.isEmpty(originalFilename)) {
                FileOutputStream fos = new FileOutputStream(originalFilename);
                BufferedOutputStream bos = new BufferedOutputStream(fos);
                InputStream is = file.getInputStream();
                int temp;
                while ((temp = is.read()) != -1) {
                    bos.write(temp);
                }

                bos.close();
                fos.close(); // 关闭FileOutputStream对象
            }
            return originalFilename;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

}
